package com.sishu.njrtsdms.service.system;

import com.sishu.njrtsdms.domain.core.LoginUser;
import com.sishu.njrtsdms.domain.vo.UserVO;
import com.sishu.njrtsdms.enums.DictDataEnum;
import com.sishu.njrtsdms.exception.ServiceException;
import com.sishu.njrtsdms.manager.DictionaryManager;
import com.sishu.njrtsdms.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author njrts-dms
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserService userService;

    private final PasswordService passwordService;

    private final DictionaryManager dictionaryManager;

    public UserDetailsServiceImpl(
            UserService userService,
            PasswordService passwordService,
            DictionaryManager dictionaryManager) {
        this.userService = userService;
        this.passwordService = passwordService;
        this.dictionaryManager = dictionaryManager;
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserVO user = userService.selectUserByUsername(username);
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        } else if (user.isDeleted()) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        } else if (user.userStatusDict().dictDataId().equals(
                dictionaryManager.getIdByEnum(DictDataEnum.DISABLED))) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }

        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(UserVO user) {
        return LoginUser.builder()
                .userId(user.userId().longValue())
                .user(user)
                .build();
    }
}
